/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Tests;

import Sorting.Main;
import com.sun.j3d.utils.geometry.Box;
import com.sun.j3d.utils.geometry.Sphere;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.swing.*;
import javax.vecmath.Vector3f;

/**
 *
 * @author rafael
 */
public class VectorThread extends Thread {
    
    public static boolean isRunning = false;
    public static Vector3f elementPosition = new Vector3f(-0.2f, 0.0f, -0.2f);

    public VectorThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        execute();
    }

    private void execute() {
        
        try {
            
            Main.textPane.setText(Main.textoBubble);
            callVectorButtons();
            Main.frame.setEnabled(false);

            BranchGroup bgroup = Main.vectorBranchGroup();
            Main.su.addBranchGraph(bgroup);

        } finally {
            Main.isRunning = false;
            Main.clearTexts();
        }
    }
    
    private static void checkElementPosition(int index) {
        
        if (index == 0) {
         elementPosition.x = -0.4f;   
        } else if (index == 1) {
         elementPosition.x = -0.2f;
        } else if (index == 2) {
         elementPosition.x = 0.0f;
        } else {
         elementPosition.x = (index * 0.2f) - 0.4f;
        }
        
    }

    public static void insertElement() {
        
        String indexString = "";
        int indexNumber = -1;

        while (indexNumber < 0 || indexNumber > 9) {
            indexString = JOptionPane.showInputDialog("Qual a posição do número adicionado? Capacidade atual: " + Main.vectorCapacity);
            
            if (indexString == null || indexString.equals("")) {    
            } else {
                indexNumber = Integer.parseInt(indexString);
            }
            
        }
        

        if (indexNumber < 0 || indexNumber > Main.vectorSize) {
        
            JOptionPane.showMessageDialog(null, "O índice não está dentro dos limites do vetor atual.");
        
        } else {
        
        
        if (Main.vectorSize == Main.vectorCapacity) {
        
            Sorting.Number number[] = new Sorting.Number[Main.vectorCapacity];
            
            for (int i = 0; i < Main.vectorCapacity; i++) {
                number[i] = Main.vetorNumeros[i];
            }
            
            Main.vectorCapacity = Main.vectorCapacity * 2;
            Main.vetorNumeros = new Sorting.Number[Main.vectorCapacity];
            
            for (int i = 0; i < Main.vectorCapacity / 2; i++) {
                Main.vetorNumeros[i] = number[i];
            }
        
        } 

        String numberString = "";
        int number = -1;

        while (number < 0 || number > 9) {
            numberString = JOptionPane.showInputDialog("Qual o número à ser adicionado?");
            
            if (numberString == null || numberString.equals("")) {    
            } else {
                number = Integer.parseInt(numberString);
            }
            
        }
        
        System.out.println("Vai adicionar o: " + number);
        
        for (int i = Main.vectorSize; i > indexNumber; i--) {
            Main.vetorNumeros[i] = Main.vetorNumeros[i - 1];
            Main.moveVectorObjectRight(Main.vetorNumeros, i, (i * 0.2f) - 0.4f);
        }
        
        BranchGroup branchGroup = new BranchGroup();

        Sphere sphere = new Sphere(Main.raio, Main.criarApp());
        sphere.setCapability(Sphere.ENABLE_APPEARANCE_MODIFY);
        Transform3D tfSphere = new Transform3D();
        checkElementPosition(indexNumber);
        tfSphere.setTranslation(new Vector3f(elementPosition.x, elementPosition.y, elementPosition.z));
        TransformGroup tgSphere = new TransformGroup(tfSphere);
        tgSphere.addChild(sphere);
        branchGroup.addChild(tgSphere);
        
        Main.vetorNumeros[indexNumber] = new Sorting.Number(number, tgSphere);
        Main.vectorSize++;
        
        Main.su.addBranchGraph(branchGroup);
        
        }
        
    }
    
    public static void popElement () {
        
        if (Main.queueSize == 0) {
            
            JOptionPane.showMessageDialog(null, "Fila vazia, não há elementos à serem retirados!");
        
        } else {
        
        Main.destroyListElement(0);
        Main.numberList.remove(0);
        Main.queueSize--;
        
        float x = -0.4f;
        
            for (int i = 0; i < Main.numberList.size(); i++) {
                Main.moveQueueObject(Main.numberList, i, x);
                x += 0.4f;
            }
            
        elementPosition.x = Main.queueSize * 0.4f - 0.8f;
        
        
        }
        
    }
    
    public static void topElement () {
        
        if (Main.numberList.isEmpty()) {
        
            JOptionPane.showMessageDialog(null, "Não há elementos na fila.");
            
        } else {
        
            JOptionPane.showMessageDialog(null, "O elemento do topo da fila é: " + Main.numberList.get(0).getNumber());
        
        }
    }
    
    public static void showElements() {
        
        if (Main.vectorSize == 0 || Main.vetorNumeros.length == 0) {
        
            JOptionPane.showMessageDialog(null, "Não há elementos no vetor.");
            
        } else {
            
            
            String numeros = "{ ";
            
                for (int i = 0; i < Main.vectorSize; i++) {
                    numeros += Main.vetorNumeros[i].getNumber() + " ";
                }
            numeros += "}";
            
            JOptionPane.showMessageDialog(null, "Elementos: " + numeros);
        
        }
        
    }

    public static void callVectorButtons() {


        JFrame frame = new JFrame("Vector Actions");

        JPanel vectorButtonsPanel = new JPanel(new GridLayout(4, 0));

        JButton addButton = new JButton("Inserir");
        JButton removeButton = new JButton("Retirar");
        JButton lastElementButton = new JButton("Último Índice");
        JButton showElementsButton = new JButton("Vector Elements");

        addButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                insertElement();
            }
        });

        removeButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                popElement();
            }
        });

        lastElementButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                topElement();
            }
        });

        showElementsButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               showElements(); 
            }
            
        });
        
        JLabel exitLabel = new JLabel("Para finalizar a execução do vetor, feche esta janela");
        JTextArea exitText = new JTextArea("Para finalizar a execução do vetor, feche esta janela");
        exitText.setEditable(false);
        exitText.setLineWrap(true);
        exitText.setAutoscrolls(true);
        vectorButtonsPanel.add(addButton);
        vectorButtonsPanel.add(removeButton);
        vectorButtonsPanel.add(lastElementButton);
        vectorButtonsPanel.add(showElementsButton);
        frame.add(vectorButtonsPanel);
        frame.setBounds(415, 60, 300, 140);

        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                    
                for (int i = 0; i < Main.numberList.size(); i++) {
//                        Main.destroyQueueObject(Main.numberList, i);
                        
                }
                Main.queueSize = 0;
                Main.isRunning = false;
                Main.clearTexts();
                Main.frame.setEnabled(true);
                
            }
        });

        frame.setResizable(false);
        frame.setVisible(true);

    }
}
